import time

import requests
import json
import random
import string
import hashlib

room_id = 'r_jr5o0r82r40100'  # 定义直播间id
send_message_num = 100  # 定义发送消息的数量
users_list = [  # 定义发消息的用户列表 【uid 昵称 是否会员】
    ('uid_604335161497247745', '默看这一切', 'false'),
    ('uid_596309448005296130', ' Olivia..', 'true'),
    ('uid_576443691880243202', '急急急', 'false'),
    ('uid_587313907518926849', 'GGBoy123哈哈哈霹雳啪啦的时候铭记噼里啪啦米沃奇无刷66😏', 'false'),
    ('uid_578620846164819970', '旺柴336666', 'false'),
    ('uid_585908909681672194', 'aabbcc321', 'false'),
    ('uid_594117890367594497', '若相惜', 'true')
]


# 发送评论
def auto_send_message(room_id, send_message_num):
    # 评论接口地址
    # url = "http://msha-test-http.rutbr.com/gateway/api/message/message/sendMessage"
    url = "https://msha-test-msg-http.rutbr.com/msgsend/message/sendMessage/batch"

    # 生成13位时间戳
    timestamp = int(time.time() * 1000)

    # 生成经过加密的签名  线上：231b8cf537e383cf9d6a69dafcf86c48   测试：fengjin_test_
    sign = f'fengjin_test_{timestamp}'
    m = hashlib.md5()
    m.update(sign.encode('utf-8'))
    sign_code = m.hexdigest()

    # 定义请求头
    headers = {
        'route_d': room_id,
        'sign_app_key': 'fengjin',
        'sign_code': sign_code,
        'sign_timestamp': str(timestamp),
        'User-Agent': 'Apifox/1.0.0 (https://apifox.com)',
        'Content-Type': 'application/json'
    }

    num = 1
    # 循环发送消息,
    for i in range(int(send_message_num)):
        now_time = time.strftime('%Y-%m-%d %H:%M:%S')
        # 生成26位小写字母和26位大写字母的数据源
        alphabet = string.ascii_lowercase + string.ascii_uppercase
        # 利用上面的数据源，生成长度为16的随机字符串用来做messageId
        random_string = ''.join(random.choices(alphabet, k=16))
        # 从定义好的用户列表中随机选一个用户
        random_users = random.choice(users_list)
        # 定义请求体
        payload = json.dumps({
            "data": [{
                "command": "MESSAGE",
                "messageId": random_string,
                "data": {
                    "textMessage": "",
                    "topic": "live.text_message",
                    "message": "{\"userId\":\"%s\",\"userName\":\"%s\",\"content\":\"%s\","
                               "\"roleCode\":3,\"messageType\":\"text\",\"isVip\":%s}" % (
                                   random_users[0], random_users[1], now_time + '   第' + str(num) + '条评论',
                                   random_users[2])
                },
                "levelCode": "B3",
                "deviceId": "device06535711680372491",
                "roomId": room_id,
                "senderId": random_users[0]
            }]
        })

        response = requests.request("POST", url, headers=headers, data=payload)
        if response.json()["state"]["msg"] == 'success':
            print(f'第{num}条消息发送成功，发送人:{random_users[1]}')
        else:
            print(response.text)

        num += 1


auto_send_message(room_id, send_message_num)
